package com.qipay.api.wx.controller.v1;

import com.qipay.api.wx.controller.v1.vo.CpPayWeiXinMpPayVo;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.pay.WeiXinMpPayService;
import com.qipay.pay.entity.CpPayWeiXinMpPayRequest;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.JWTUser;
import com.qipay.sp.SpApiConfigService;
import com.qipay.sp.SpConfigService;
import com.qipay.sp.SpService;
import com.qipay.sp.excutor.ExcutorFactory;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MpPayController
 *
 * @author ansen
 * @date 2016/10/31
 */

@RestController
@RequestMapping("/sig/v1/wx")
public class MpPayController {
    private final Log logger = LogFactory.getLog(this.getClass());

    private final static String CONFIG_JS_NAME = "is_raw";

    @Value("${api.response.sign.name}")
    String apiResponseSignName;

    @Value("${api.response.key.name}")
    String apiResponseKeyName;

    @Value("${api.mp.pay.spconfig.appid.key}")
    String apiMpPaySpconfigAppIdKey;

    @Value("${api.mp.pay.openid.callback.url}")
    String apiMpPayOpenIdCallbackUrl;

    @Value("${api.host.key.name}")
    String apiHostKeyName;

    @Autowired
    WeiXinMpPayService weiXinMpPayService;

    @Autowired
    SpConfigService spConfigService;

    @Autowired
    SpService spService;

    @Autowired
    SpApiConfigService spApiConfigService;



    @RequestMapping(value = "/mp", method = RequestMethod.POST, produces = {"application/xml;charset=UTF-8"})
    private String unionCreate(
            HttpServletRequest request,
            HttpServletResponse response,
            @AuthenticationPrincipal JWTUser user
    ) throws Exception {

        Map<String, Object> params = (Map<String, Object>) request.getAttribute("params");
        CpPayWeiXinMpPayVo vo = (CpPayWeiXinMpPayVo) XmlUtils.mapToBean(
                params, CpPayWeiXinMpPayVo.class);
        CpPayWeiXinMpPayRequest bean = new CpPayWeiXinMpPayRequest();
        BeanUtils.copyProperties(vo, bean);

        Order order = weiXinMpPayService.jspayCreateOrder(bean, user);

        Map<String, Object> result = null;
        String isRaw = spConfigService.getValue(order.getSpId(),MpPayController.CONFIG_JS_NAME);
        if("0".equals(isRaw)){
            result = excuteFactoryExcutor(order);
        }else{
            String appid = spConfigService.getValue(order.getSpId(), apiMpPaySpconfigAppIdKey);
            Assert.notNull(appid, "该SP没有配置公众号的AppId");
            String host = spConfigService.getValue(order.getSpId(), apiHostKeyName);
            Assert.notNull(host, "该SP没有配置公众号的Host");
            String callBackUrl = StringUtils.replace(apiMpPayOpenIdCallbackUrl,apiHostKeyName,host);
            Assert.notNull(callBackUrl, "该SP没有配置公众号的callBackUrl");

            String redirectUrl =  String.format("https://open.weixin.qq.com/connect/oauth2/authorize?" +
                            "appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%d#wechat_redirect",
                    appid, URLEncoder.encode(callBackUrl, "UTF-8"), order.getId());
            result = new HashMap<>();
            result.put("redirect_url",redirectUrl);
            result.put("result_code", "0");
        }

        result = ResultUtils.wrapResult(ApiStatusEnum.OK.getCode().toString(), null, result);
        result = ResultUtils.signResult(result, user.getSecret(),apiResponseSignName, apiResponseKeyName);
        return XmlUtils.toString(result, "xml");
    }

    public Map<String, Object> excuteFactoryExcutor(Order order) throws Exception {
        Map<String, Object> result = null;
        try {
            ExcutorFactory excutorFactory = spService.getFactory(order.getSpId());
            result = excutorFactory.createWxMpPayExcutor().excutor(order);
        }catch (Exception ex) {
            ex.printStackTrace();
            logger.error(order.getTradeNo() + ":" + order.getChannelType().toString()
                    + " -- 执行工厂方法出错:" + ex.toString());
        }
        return result;
    }


}
